package itsm.isperp.module.controller.screen;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.entity.incident.IcdMajorChat;
import itsm.isperp.module.entity.incident.IcdMajorHandle;
import itsm.isperp.module.entity.kpi.KpiSetting;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.incident.IcdMajorChatService;
import itsm.isperp.module.service.incident.IcdMajorHandleService;
import itsm.isperp.module.service.kpi.KpiSettingService;
import itsm.isperp.report.IDataResolver;
import itsm.isperp.report.resolver.DataResolver;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.abel533.echarts.json.GsonOption;

@Controller
@RequestMapping("screen/screen")
public class ScreenScreenController {

  @Autowired
  JdbcTemplate jdbcTemplate;

  @RequestMapping("mainframe")
  public ModelAndView mainframe() {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("screen/screen/mainframe");
    return mv;
  }

  /**
   * 大屏
   * 
   * @return
   */
  @RequestMapping("main")
  public ModelAndView screenMain() {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("screen/screen/main");
    return mv;
  }

  @RequestMapping("incidentMajors")
  @ResponseBody
  public List<Map<String, Object>> incidentMajors() {

    String sql = "SELECT id FROM icd_incident WHERE status<>'已关闭' AND are_major=1";
    return jdbcTemplate.queryForList(sql);
  }

  /**
   * 重要事件大屏
   * 
   * @return
   */
  @RequestMapping("incidentMajor")
  public ModelAndView major(String id) {
    ModelAndView mv = new ModelAndView();
    IcdIncidentService icdIncidentService = ContextHolder
        .getSpringBean("icdIncidentService");
    IcdIncident model = icdIncidentService.findOne(id);
    mv.addObject("model", model);

    mv.setViewName("screen/screen/incidentMajor");
    return mv;
  }

  /**
   * 重要事件成员
   * 
   * @return
   */
  @RequestMapping("incidentMajorMember")
  @ResponseBody
  public List<Map<String, Object>> incidentMajorMember(String id) {

    String strQueryGroupByStatus = "SELECT a.username,b.fullname,b.department_treenode_name_path,b.position FROM icd_major_member a LEFT JOIN app_user b ON a.username=b.name WHERE a.incident_id='"
        + id + "' ORDER by a.order_num  ";

    List<Map<String, Object>> list = this.jdbcTemplate
        .queryForList(strQueryGroupByStatus);

    return list;

  }

  @RequestMapping("incidentMajorHandle")
  @ResponseBody
  public List<IcdMajorHandle> majorHandle(String id) {
    IcdMajorHandleService icdMajorHandleService = ContextHolder
        .getSpringBean("icdMajorHandleService");

    return icdMajorHandleService.findAllByIncidentId(id);

  }

  @RequestMapping("incidentMajorChats")
  @ResponseBody
  public List<IcdMajorChat> majorChats(String id, String time) {
    IcdMajorChatService icdMajorChatService = ContextHolder
        .getSpringBean("icdMajorChatService");

    return null;

  }

  /**
   * 总数统计
   * 
   * @return
   */
  @SuppressWarnings("deprecation")
  @RequestMapping("totals")
  @ResponseBody
  public Map<String, Integer> totals() {

    String strQueryGroupByStatus = "SELECT status,count(status) count_t FROM icd_incident WHERE status<>'已关闭'  GROUP BY status ";
    String strQueryForInt = "SELECT count(1) FROM icd_incident WHERE status<>'已关闭'";
    
    Map<String, Integer> result = new HashMap<String, Integer>();
    result.put("i_assign", 0);
    result.put("i_accept", 0);
    result.put("i_handle", 0);
    result.put("i_approval", 0);
    result.put("i_handup", 0);
    result.put("i_vip", 0);
    result.put("i_complaint", 0);
    result.put("i_count", 0);

    result.put("p_approval", 0);
    result.put("p_handle", 0);

    result.put("c_approval", 0);
    result.put("c_handle", 0);
    
    result.put("r_approval", 0);
    result.put("r_handle", 0);

    List<Map<String, Object>> statusList = jdbcTemplate
        .queryForList(strQueryGroupByStatus);
    Integer countAll = jdbcTemplate.queryForObject(strQueryForInt,Integer.class);
    result.put("i_count",result.get("i_count") + countAll);
    
    for (Map<String, Object> st : statusList) {
      String status = (String) st.get("status");

      int countStatus = Integer.parseInt(st.get("count_t").toString());
      if (status == null) {
        continue;
      }
      switch (status) {
      case "一线处理":
      case "三线处理":
      case "二线处理":
      case "待分派":
      case "新建":
        result.put("i_assign", result.get("i_assign") + countStatus);
        break;
      case "已登记":
      case "待受理":
      case "待响应":
        result.put("i_accept", result.get("i_accept") + countStatus);
        break;
      case "已到场":
      case "待处理":
        result.put("i_handle", result.get("i_handle") + countStatus);
        break;
      case "挂起中":
        result.put("i_handup", result.get("i_handup") + countStatus);
        break;
      case "事件回访":
      case "待回访":
        result.put("i_complaint", result.get("i_complaint") + countStatus);
        break;
      }
    }

    // ---vip
    String strQueryVipCount = "SELECT  count(*) count_t FROM icd_incident a WHERE a.are_vip=1 AND  a.status<>'已关闭'";
    result.put(
        "i_vip",
        result.get("i_vip")
            + jdbcTemplate.queryForObject(strQueryVipCount,
                Integer.class));

    // --服务请求
    String strQueryComplaintCount = "SELECT  count(*) count_t FROM icd_incident WHERE incident_type='服务请求' AND status<>'已关闭'";
    result.put(
        "i_complaint",
        result.get("i_complaint")
            + jdbcTemplate.queryForObject(strQueryComplaintCount,
                Integer.class));

    String strQueryChangeGroupByStatus = "SELECT status,count(status) count_t FROM chg_change WHERE status<>'已关闭'  GROUP BY status ";

    List<Map<String, Object>> changeStatusList = jdbcTemplate
        .queryForList(strQueryChangeGroupByStatus);

    for (Map<String, Object> st : changeStatusList) {
      String status = (String) st.get("status");
      int countStatus = Integer.parseInt(st.get("count_t").toString());

      if (status.contains("实施") || status.contains("测试") || status.contains("制定")) {
        result.put("c_handle", result.get("c_handle") + countStatus);
      } else{
        result.put("c_approval", result.get("c_approval") + countStatus);
      }
    }

    String strQueryProblemGroupByStatus = "SELECT status,count(status) count_t FROM prob_problem WHERE status<>'已关闭'  GROUP BY status";
    List<Map<String, Object>> problemStatusList = jdbcTemplate
        .queryForList(strQueryProblemGroupByStatus);

    for (Map<String, Object> st : problemStatusList) {
      String status = (String) st.get("status");
      int countStatus = Integer.parseInt(st.get("count_t").toString());

      
      if (status.contains("评审") || status.contains("评估") || status.contains("验证")) {
        result.put("p_approval", result.get("p_approval") + countStatus);
      } else {
        result.put("p_handle", result.get("p_handle") + countStatus);
      }
    }
    
    String strQueryRealizeGroupByStatus = "SELECT status,count(status) count_t FROM rls_release WHERE status<>'已关闭'  GROUP BY status";
    List<Map<String, Object>> realizeStatusList = jdbcTemplate
        .queryForList(strQueryRealizeGroupByStatus);
    
    for (Map<String, Object> st : realizeStatusList) {
      String status = (String) st.get("status");
      int countStatus = Integer.parseInt(st.get("count_t").toString());

      
      if (status.contains("计划") || status.contains("回顾")) {
        result.put("r_approval", result.get("r_approval") + countStatus);
      } else {
        result.put("r_handle", result.get("r_handle") + countStatus);
      }
    }
    
    
    
    return result;
  }

  @RequestMapping("top10")
  @ResponseBody
  public List<Map<String, Object>> top10(String type) {
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    String sql = "";

    switch (type) {
    /*case "1":
      sql = "SELECT b.DEPARTMENT_TREENODE_NAME_PATH dept, COUNT(*)   count_t FROM icd_incident a INNER JOIN app_user b ON a.supporter_id=b.name  WHERE a.status IN ('二线处理','二线受理') GROUP BY  DEPARTMENT_TREENODE_NAME_PATH";
      List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

      Map<String, Counter> support = new HashMap<String, Counter>();

      for (Map<String, Object> m : list) {

        String deptPath = m.get("dept").toString();
        String dept = deptPath.split("/")[3];

        if (support.containsKey(dept)) {
          support.get(dept).setCount(
              Integer.parseInt(m.get("count_t").toString())
                  + support.get(dept).getCount());
        } else {
          support.put(
              dept,
              new Counter(dept, Integer.parseInt(m.get("count_t")
                  .toString()), 0));
        }

      }

      Map<String, Counter> sortedMap = SortAnalyzer.sortMapByCount(support);

      int i = 0;
      if (sortedMap != null) {
        for (String key : sortedMap.keySet()) {
          Map<String, Object> m = new HashMap<String, Object>();
          m.put("name", key);
          m.put("count_t", sortedMap.get(key).getCount());
          result.add(m);

          i++;

          if (i == 10) {
            break;
          }
        }
      }

      break;*/
    case "1":
      sql = "SELECT CASE when fn_splitString(icd_category_name,'/','3')='' then '其他' when fn_splitString(icd_category_name,'/','3') is null then '其他' else fn_splitString(icd_category_name,'/','3') END name,COUNT(*) count_t FROM icd_incident WHERE status<>'已关闭'  GROUP BY name ORDER BY count_t DESC limit 10";
      result = jdbcTemplate.queryForList(sql);
      break;
    case "2":
      sql = "SELECT CASE WHEN b.name IS NULL THEN '其他' ELSE b.name END name,count(1) count_t FROM `icd_incident` a LEFT JOIN `proj_project` b ON a.project_id = b.id WHERE a.status<>'已关闭' GROUP BY name ORDER BY count_t DESC";
      result = jdbcTemplate.queryForList(sql);
      break;
    }

    return result;
  }
  @RequestMapping("knotop10")
  @ResponseBody
  public List<Map<String, Object>> knotop10(String type){
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    String sql = "";
    switch(type){
    case "1":
      sql = "SELECT CASE WHEN c.name IS NULL THEN '其他' ELSE c.name END name,count(1) count_t FROM kng_knowledge_item a LEFT JOIN app_user b ON a.creator_name = b.fullname LEFT JOIN app_department c ON b.app_department_id = c.id GROUP BY name ORDER BY count_t DESC";
      result = jdbcTemplate.queryForList(sql);
      break;
    case "2":
      sql = "SELECT CASE WHEN b.name IS NULL THEN '其他' ELSE b.name END name,count(1) count_t FROM kng_knowledge_item a LEFT JOIN kng_knowledge_category b ON a.kng_knowledge_category_id = b.id GROUP BY b.name ORDER BY count_t DESC";
      result = jdbcTemplate.queryForList(sql);
      break;
    }
    
    return result;
  }
  
  @RequestMapping("top10System")
  @ResponseBody
  public List<Map<String, Object>> top10System() {
    String sql = "select count(1) count_t,creator_name name from`kng_knowledge_item` where date_format(publish_date,'%m')= date_format(curdate(),'%m') and date_format(curdate(),'%Y') = date_format(publish_date,'%Y') group by creator_name ORDER BY count_t DESC limit 0,10";

    return jdbcTemplate.queryForList(sql);
  }

  @RequestMapping("dayOfMonthTotal")
  @ResponseBody
  public Map<String, Object> dayOfMonthTotal() {

    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
    SimpleDateFormat sfy = new SimpleDateFormat("yyyy");

    String toMonth = sf.format(new Date());
    String toYear = sfy.format(new Date());

    /*String queryIncident = "SELECT DATE_FORMAT(create_date,'%Y-%m') cdate, count(incident_type) count_t FROM icd_incident"
        + " WHERE '"
        + "2015-07"
        + "'= DATE_FORMAT( create_date ,'%Y-%m') AND incident_type IN('故障','问询','需求') "
        + " GROUP BY DATE_FORMAT(create_date,'%Y-%m'),incident_type ";*/
    /*String queryProblem = "SELECT DATE_FORMAT(create_date,'%Y-%m') cdate, count(*) count_t FROM prob_problem "
    + " WHERE '"
    + toMonth
    + "'= DATE_FORMAT( create_date ,'%Y-%m') "
    + " GROUP BY DATE_FORMAT(create_date,'%Y-%m') ";

    String queryChange = "  SELECT DATE_FORMAT(create_date,'%Y-%m') cdate, count(*) count_t FROM chg_change "
    + " WHERE '"
    + toMonth
    + "'= DATE_FORMAT( create_date ,'%Y-%m') "
    + " GROUP BY DATE_FORMAT(create_date,'%Y-%m') ";*/
    String queryIncident = "SELECT DATE_FORMAT(create_date,'%Y-%m') cdate, count(1) count_t FROM icd_incident"
        + " WHERE '"
        + toYear
        + "'= DATE_FORMAT( create_date ,'%Y') GROUP BY cdate";
    
    String queryProblem = "SELECT DATE_FORMAT(create_date,'%Y-%m') cdate, count(1) count_t FROM prob_problem WHERE '"+toYear+"'= DATE_FORMAT( create_date ,'%Y') GROUP BY cdate ";

    String queryChange = "SELECT DATE_FORMAT(create_date,'%Y-%m') cdate, count(1) count_t FROM chg_change WHERE '"+toYear+"'= DATE_FORMAT( create_date ,'%Y') GROUP BY cdate ";

    String queryCalendar = "SELECT DATE_FORMAT( calendar_date ,'%Y-%m') cdate FROM APP_CALENDAR_DAY a   WHERE '"
        + toYear
        + "'= DATE_FORMAT( calendar_date ,'%Y') AND calendar_date<=NOW() GROUP BY cdate ORDER BY cdate ";
    // 工作日历
    List<String> dates = jdbcTemplate.queryForList(queryCalendar,
        String.class);

    List<Map<String, Object>> list1 = jdbcTemplate
        .queryForList(queryIncident);

    List<Map<String, Object>> list2 = jdbcTemplate
        .queryForList(queryChange);
    
    List<Map<String, Object>> list3 = jdbcTemplate
        .queryForList(queryProblem);

    List<Integer> data1 = new ArrayList<Integer>();
    List<Integer> data2 = new ArrayList<Integer>();
    List<Integer> data3 = new ArrayList<Integer>();
  
    Map<String, Integer> m = new LinkedHashMap<>();
    Map<String, Integer> m2 = new LinkedHashMap<>();
    Map<String, Integer> m3 = new LinkedHashMap<>();

    for (Map<String, Object> map : list1) {
      String cdate = map.get("cdate").toString();
      int count_t = Integer.parseInt(map.get("count_t").toString());
      m.put(cdate, count_t);
    }
    for (Map<String, Object> map : list2) {
      String cdate = map.get("cdate").toString();
      int count_t = Integer.parseInt(map.get("count_t").toString());
      m2.put(cdate, count_t);
    }
    for (Map<String, Object> map : list3) {
      String cdate = map.get("cdate").toString();
      int count_t = Integer.parseInt(map.get("count_t").toString());
      m3.put(cdate, count_t);
    }
    for (String s : dates) {
      if(m.containsKey(s)){
        data1.add(m.get(s)==null?0:m.get(s));
      }else{
        data1.add(0);
      }
      if(m2.containsKey(s)){
        data2.add(m2.get(s)==null?0:m2.get(s));
      }else{
        data2.add(0);
      }
      if(m3.containsKey(s)){
        data3.add(m3.get(s)==null?0:m3.get(s));
      }else{
        data3.add(0);
      }
    }
    Map<String, Object> result = new HashMap<String, Object>();
    
    List<String> data0 = new ArrayList<String>();
    for(String s:dates){
      String[] split = s.split("-");
      String month = split[1];
      int charAt = Integer.parseInt(String.valueOf(month.charAt(0)));
      if(charAt==0){
        data0.add(month.charAt(1)+"月");
      }else{
        data0.add(month+"月");
      }
    }
    result.put("date0", data0);

    result.put("data1", data1);
    result.put("data2", data2);
    result.put("data3", data3);
    
    /*List<Integer> data1 = new ArrayList<Integer>();
    List<Integer> data2 = new ArrayList<Integer>();
    List<Integer> data3 = new ArrayList<Integer>();
    List<Integer> data4 = new ArrayList<Integer>();
    List<Integer> data5 = new ArrayList<Integer>();

    Map<String, Map<String, Integer>> m = new LinkedHashMap<>();
    Map<String, Map<String, Object>> m2 = new LinkedHashMap<>();
    Map<String, Map<String, Object>> m3 = new LinkedHashMap<>();

    // 事件
    for (Map<String, Object> map : list1) {
      String cdate = map.get("cdate").toString();
      String incident_type = map.get("incident_type").toString();
      int count_t = Integer.parseInt(map.get("count_t").toString());

      if (m.containsKey(cdate)) {
        m.get(cdate).put(incident_type, count_t);
      } else {
        Map<String, Integer> mm = new HashMap<String, Integer>();
        mm.put(incident_type, count_t);
        m.put(cdate, mm);
      }
    }
    // 变更
    for (Map<String, Object> map : list2) {
      String cdate = map.get("cdate").toString();
      m2.put(cdate, map);
    }
    // 问题
    for (Map<String, Object> map : list3) {
      String cdate = map.get("cdate").toString();
      m3.put(cdate, map);
    }

    for (String s : dates) {
      if (m.containsKey(s)) {
        Map<String, Integer> map = m.get(s);
        data1.add(map.get("故障") == null ? 0 : map.get("故障"));
        data2.add(map.get("需求") == null ? 0 : map.get("需求"));
        data3.add(map.get("问询") == null ? 0 : map.get("问询"));
      } else {
        data1.add(0);
        data2.add(0);
        data3.add(0);
      }
      if (m2.containsKey(s)) {
        Map<String, Object> map = m2.get(s);
        int count_t = Integer.parseInt(map.get("count_t").toString());
        data4.add(count_t);
      } else {
        data4.add(0);
      }

      if (m3.containsKey(s)) {
        Map<String, Object> map = m3.get(s);
        int count_t = Integer.parseInt(map.get("count_t").toString());
        data5.add(count_t);
      } else {
        data5.add(0);
      }
    }

    Map<String, Object> result = new HashMap<String, Object>();
    result.put("dates", dates);

    result.put("data1", data1);
    result.put("data2", data2);
    result.put("data3", data3);
    result.put("data4", data4);
    result.put("data5", data5);*/
    return result;
  }
  

  @RequestMapping("performance")
  @ResponseBody
  public Map<String, GsonOption> performance(HttpServletRequest req)
      throws ParseException {

    Map<String, GsonOption> m=new HashMap<String,GsonOption>();
    return m;
  }

  /*@RequestMapping(value = { "incidentMajorList" })
  @ResponseBody
  public List<Map<String, Object>> majorList(HttpServletRequest req) {

    //String sql = "SELECT id,title,confirmtimeman_name,happen_time FROM icd_incident WHERE status='担当判定'  ";
    String sql = "select id from icd_incident";
    return jdbcTemplate.queryForList(sql);

  }*/

}
